package com.xzakota.minesweeper.ui.dialog;

import com.xzakota.minesweeper.App;
import com.xzakota.minesweeper.Client;
import com.xzakota.minesweeper.contant.ConstantPool;
import com.xzakota.minesweeper.model.entity.UserBean;
import com.xzakota.minesweeper.msg.*;
import com.xzakota.minesweeper.ui.dialog.templae.AbstractBaseDialog;
import com.xzakota.minesweeper.ui.dialog.templae.MessageDialog;
import com.xzakota.minesweeper.ui.dialog.templae.SwingWorkerWaitDialog;
import com.xzakota.minesweeper.util.JSONFileUtils;
import com.xzakota.minesweeper.util.StringUtils;
import com.xzakota.minesweeper.widget.text.InputTextField;

import javax.swing.*;
import java.awt.*;
import java.util.concurrent.CountDownLatch;

/**
 * 登录对话框
 *
 * @author Xzakota
 */
public class SignInDialog extends AbstractBaseDialog {
    public SignInDialog(Window parent) {
        super(parent);

        setTitle("登录");
        setMessage("无需复杂步骤，登录开启无限可能！\n");
        setMinimumSize(new Dimension(250, 200));

        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));

        InputTextField usernameTextField = new InputTextField("昵称: ", false);
        if (JSONFileUtils.has(ConstantPool.SETTINGS_USER_NAME)) {
            usernameTextField.setFieldText(JSONFileUtils.getString(ConstantPool.SETTINGS_USER_NAME));
        }
        usernameTextField.setHintText("");
        mainPanel.add(usernameTextField);

        InputTextField passwordTextField = new InputTextField("密码: ", true);
        passwordTextField.setHintText("");
        mainPanel.add(passwordTextField);

        setComponent(mainPanel);
        setConfirmButton("登录");
        setConfirmAction(e -> {
            usernameTextField.setHintText("");
            passwordTextField.setHintText("");

            String username = usernameTextField.getFieldText();
            String password = passwordTextField.getFieldText();

            if (StringUtils.isInvalid(username, "^[a-zA-Z0-9]{5,8}$")) {
                usernameTextField.setHintText("昵称不合法", Color.RED);
                return;
            }

            if (StringUtils.isInvalid(password, "^[a-zA-Z0-9]{6,8}$")) {
                passwordTextField.setHintText("密码不合法", Color.RED);
                return;
            }

            if (App.connectServer()) {
                return;
            }

            SwingWorkerWaitDialog waitDialog = new SwingWorkerWaitDialog();
            waitDialog.setTipText("正在登录中...");
            waitDialog.worker = new SwingWorkerWaitDialog.Worker() {
                @Override
                public Boolean doInBackground() {
                    SignInMsg sendMsg = new SignInMsg();
                    sendMsg.data = new UserBean(username, password);

                    final Object[] result = new Object[2];

                    CountDownLatch latch = new CountDownLatch(1);
                    waitDialog.doReleaseEvent();
                    waitDialog.tempThread = new Thread(() -> {
                        Client client = Client.getClient();
                        while (client.socketState != 1 && !Thread.currentThread().isInterrupted()) {
                        }
                        MsgHandler handler = new MsgHandler() {
                            @Override
                            public void handle(BaseMsg msg) {
                                if (msg.code == MsgCode.BASE_SUCCESS) {
                                    result[0] = true;
                                    result[1] = msg.data;
                                } else {
                                    result[0] = false;
                                }
                                new MessageDialog(SignInMsgDefaultHandler.resultMsgText).showWindow();
                                MsgHandlerFactory.removeMsgHandler(MsgHandlerFactory.MSG_TYPE_SIGN_IN, this);
                                latch.countDown();
                            }
                        };
                        MsgHandlerFactory.addMsgHandler(MsgHandlerFactory.MSG_TYPE_SIGN_IN, handler);
                        Client.getClient().sendMsg(sendMsg);
                    });
                    waitDialog.tempThread.start();

                    try {
                        latch.await();
                    } catch (InterruptedException ex) {
                        throw new RuntimeException(ex);
                    }

                    if (result[0] instanceof Boolean && (Boolean) result[0]) {
                        JSONFileUtils.put(ConstantPool.SETTINGS_USER_NAME, username, true);
                        JSONFileUtils.put(ConstantPool.SETTINGS_USER_HAS_SIGN_IN, true, true);
                        Client.getClient().currentUser = (UserBean) result[1];
                        return true;
                    } else {
                        return false;
                    }
                }

                @Override
                public void doneSuccess() {
                    dialogResult = true;
                    closeWindow();
                }

                @Override
                public void doneFail() {
                    dialogResult = false;
                }
            };
            waitDialog.showWindow();
        });
        setCancelButton("注册");
        setCancelAction(e -> {
            new SignUpDialog(this).showWindow();
        });
    }
}
